package cn.tedu.autoshow.website.repository.impl;

import cn.tedu.autoshow.commons.constants.JwtCacheConsts;
import cn.tedu.autoshow.commons.pojo.po.LoginInfoPO;
import cn.tedu.autoshow.website.repository.IAdminJwtRepository;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Repository;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;

@Repository
public class AdminJwtRepositoryImpl implements IAdminJwtRepository, JwtCacheConsts {

    @Autowired
    private RedisTemplate<String, Serializable> redisTemplate;

    @Override
    public LoginInfoPO getLoginInfo(String jwt, LoginInfoPO loginSimpleInfo) {
        HashOperations<String, Object, Object> operations = redisTemplate.opsForHash();
        String userTokenKey = LOGIN_HASH_ADMIN_PREFIX+loginSimpleInfo.getId();

        LoginInfoPO loginInfoPO = (LoginInfoPO) operations.get(userTokenKey, jwt);
        if(loginInfoPO == null){
            return null;
        }
        Integer enabled = (Integer) operations.get(userTokenKey, "enable");
        String authorityListJsonString = (String) operations.get(userTokenKey, "authorities");

        List<SimpleGrantedAuthority> authorities = JSON.parseArray(authorityListJsonString, SimpleGrantedAuthority.class);
        loginInfoPO.setEnable(enabled).setAuthorities(authorities);

        return loginInfoPO;
    }



}
